function [F] = MyKFottimilsqnlfmin(x, Ri_OlS, RI_OlS, nn, Params)

    %Kalman Filter Functions loglikelood
    %--------------------------------------------------------------------------
    %Initial Conditions
    x(1) = Params(1);		% phi
    x(2) = Params(2);		% beta mu
    x(3) = Params(3);
    x(4) = Params(4);		% beta mu t - 1
    x(5) = Params(5);		% Sigma t - 1
    x(6) = Params(6);		% sigma_n^2
    x(7) = Params(7);
    %Prediction Equations
    beta_t_1(1) = (1 - x(1)) * x(2) + x(1) * x(4);
    SIGMA_t_1(1) = (x(1)^2) * x(5) + x(6);
    Et_1_Rt(1) = x(3) + x(4).* (RI_OlS(1, :));
    %Updating equations
    vt(1) = Ri_OlS(1) - Et_1_Rt(1);
    ft(1) = (RI_OlS(1).^2).* (x(5)) + x(7);
    %Matrix KALMAN GAIN 
    kt(1) = RI_OlS(1).* (x(5)) / ft(1);
    beta_t(1) = beta_t_1(1) + (kt(1).* vt(1));
    SIGMA_t(1) = SIGMA_t_1(1).* (1 - SIGMA_t_1(1) * (RI_OlS(1).^2) / ft(1));
    %MAX Verosomiglianza
    LOGMAx(1) = - log(2*pi) - log(abs(ft(1))) - (vt(1).^2)./(ft(1));
    LOGverMAx(1) = LOGMAx(1)./2;
    stad(1) = vt(1)./ sqrt(ft(1));
    LOGMAx(1) = -log(2*pi)...
              -log(abs((RI_OlS(1).^2).* (x(5)) + x(7)))...
              -((Ri_OlS(1) - (x(3) + x(4).* (RI_OlS(1, :)))).^2)./ ((RI_OlS(1).^2).* (x(5)) + x(7));
    V(1) = LOGMAx(1)./ 2;

    for i=2:nn
          %Updating Equations    
          beta_t_1(i) = (1 - x(1)) * x(2) + x(1) * beta_t(i - 1);
          SIGMA_t_1(i) = (x(1)^2) * SIGMA_t(i - 1) + x(6);
          Et_1_Rt(i) = x(3) + beta_t_1(i).* (RI_OlS(i));
         %Updating equations
          vt(i) = Ri_OlS(i) - Et_1_Rt(i);
          ft(i) = (RI_OlS(i).^2).* (SIGMA_t_1(i)) + x(7);
          %Matrix KALMAN GAIN 
          kt(i) = RI_OlS(i).* (SIGMA_t_1(i)) / ft(i);
          beta_t(i) = beta_t_1(i) + (kt(i).* vt(i));
          SIGMA_t(i) = SIGMA_t_1(i).* (1 - SIGMA_t_1(i) * (RI_OlS(i).^2) / ft(i));
          %MAX Verosomiglianza
          LOGMAx(i) = -log(2 * pi) -log(abs(ft(i))) - (vt(i).^2)./ (ft(i));    
          LOGverMAx(i) = LOGMAx(i)./ 2 + LOGverMAx(i - 1);
          stad(i) = vt(i)./ sqrt(ft(i));
          LOGMAx(i) = -log(2 * pi)...
                -log(abs(((RI_OlS(i).^2).* ((x(1)^2) * (SIGMA_t(i - 1)) + x(6)) + x(7))))...
                -((Ri_OlS(i) - (x(3) + ((1 - x(1)) * x(2) + x(1) * beta_t(i - 1)).* (RI_OlS(i)))).^2)./ (ft(i));
          V(i) = LOGMAx(i)./ 2;

    end
    F = sum(V);

end